package com.jspgou.cms.action.store;

import static com.jspgou.cms.Constants.STORE_SYS;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspgou.cms.entity.Role;
import com.jspgou.cms.entity.ShopConfig;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.RoleMng;
import com.jspgou.cms.manager.ShopMemberMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.UserMng;
import com.jspgou.core.web.WebErrors;
import com.jspgou.core.web.front.FrontHelper;

@Controller
public class EmployeeAct {
	   private static final Logger log=LoggerFactory.getLogger(EmployeeAct.class);
	   
	 	/**
	  	 * 店铺子账号添加页
	  	 */
	  	private static final String TPL_EMPLOYEE_SOTER_ADD="tpl.employeeStoreAdd";
	 	/**
	 	 * 店铺子账号修改页
	 	 */
	 	private static final String TPL_EMPLOYEE_STORE_EDIT="tpl.employeeStoreEdit";
	 	/**
	 	 * 店铺子账号列表页
	 	 */
	 	private static final String TPL_EMPLOYEE_STORE_LIST="tpl.employeeStoreList";
	 	/**
	 	 * 店铺子账号密码修改页
	 	 */
	 	private static final String TPL_EMPLOYEE_STORE_PASSWORD="tpl.employeeStorePassword";;
	 	
	    @RequestMapping(value="/employee/list.jspx")
	    public String roleFroList(String cl,Integer pageNo,HttpServletRequest request,
	   		 HttpServletResponse response,ModelMap model){
	   	 Website web=SiteUtils.getWeb(request);
	   	 ShopMember member=CmsUtils.getMember(request);
	   	 //用户没有登录，跳转到登录页
	   	 if(member==null){
	   		 return ShopFrontHelper.showLogin(request, model, web);
	   	 }
	   	Store store=member.getStore();
		model.addAttribute("store", store);
		model.addAttribute("cl", cl);
	   	 ShopFrontHelper.setCommonData(request, model, web);
	   	 ShopFrontHelper.frontPageData(request, model);
	   	 return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_EMPLOYEE_STORE_LIST), request);
	    }
	    
	    @RequestMapping(value="/employee/add.jspx")
	    public String roleFroAdd(HttpServletRequest request,
	   		 HttpServletResponse response,ModelMap model){
	   	 Website web=SiteUtils.getWeb(request);
	   	 ShopMember member=CmsUtils.getMember(request);
	   	 //用户没有登录，跳转到登录页
	   	 if(member==null){
	   		 return ShopFrontHelper.showLogin(request, model, web);
	   	 }
	   	 Store store=member.getStore();
	   	 model.addAttribute("store", store);
	     List<Role> list=roleMng.getList(web.getId(), store.getId());
	     model.addAttribute("list", list);
	   	 ShopFrontHelper.setCommonData(request, model, web);
	   	 ShopFrontHelper.frontPageData(request, model);
	   	 return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_EMPLOYEE_SOTER_ADD), request);
	    }
	    
		@RequestMapping("/employee/delete.jspx")
		public String delete(Long[] ids, HttpServletRequest request,
				ModelMap model) {
			ShopMember[] beans = manager.deleteByIds(ids);
			for (ShopMember bean : beans) {
				log.info("delete CmsRole id={}", bean.getId());
			}
			return roleFroList(null,1, request, null, model);
		}
	    
	    @RequestMapping(value="/employee/save.jspx")
	    public String roleFroSave( String username,String email, String password,String realName,Long[] roleIds,
	    		HttpServletRequest request,HttpServletResponse response,
	    		ModelMap model){
	   	 Website web=SiteUtils.getWeb(request);
	   	 ShopConfig config = SiteUtils.getConfig(request);
	   	 ShopMember member=CmsUtils.getMember(request);
	   	 //用户没有登录，跳转到登录页
	   	 if(member==null){
	   		 return ShopFrontHelper.showLogin(request, model, web);
	   	 }
	   	 Store store=member.getStore();
	   	 //店铺权限划分有问题
	     manager.register(username, password, email,true,null,roleIds,
				realName,request.getRemoteAddr(), false, web.getId(), config.getRegisterGroup().getId(),store);
	   	 ShopFrontHelper.setCommonData(request, model, web);
	   	 ShopFrontHelper.frontPageData(request, model);
	   	 return "redirect:list.jspx";
	    }
	    
	    @RequestMapping(value="/employee/edit.jspx")
	    public String roleFroEdit(Long id,HttpServletRequest request,
	   		 HttpServletResponse response,ModelMap model){
	   	 Website web=SiteUtils.getWeb(request);
	   	 ShopMember member=CmsUtils.getMember(request);
	   	 //用户没有登录，跳转到登录页
	   	 if(member==null){
	   		 return ShopFrontHelper.showLogin(request, model, web);
	   	 }
	   	 ShopMember bean =manager.findById(id);
	   	 model.addAttribute("bean", bean);
	   	 Store store=member.getStore();
	   	 model.addAttribute("store", store);
	   	 //角色权限
	     List<Role> list=roleMng.getList(web.getId(), store.getId());
	     model.addAttribute("list", list);
	   	 ShopFrontHelper.setCommonData(request, model, web);
	   	 ShopFrontHelper.frontPageData(request, model);
	   	 return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_EMPLOYEE_STORE_EDIT), request);
	    }
	    
	    @RequestMapping(value="/employee/update.jspx")
	    public String roleFroUpdate(ShopMember bean,Long[] roleIds,HttpServletRequest request,
	   		 HttpServletResponse response,ModelMap model){
	   	 Website web=SiteUtils.getWeb(request);
	   	 ShopMember member=CmsUtils.getMember(request);
	   	 //用户没有登录，跳转到登陆页
	   	 if(member==null){
	   		 return ShopFrontHelper.showLogin(request, model, web);
	   	 }
	   	 if(bean.getRoles()!=null){
	   		bean.getRoles().clear();
	   	 }
	   	 
	   	 for (int i = 0; i < roleIds.length; i++) {
	   		bean.addToRoles(roleMng.findById(roleIds[i]));
	   	 }
	   	 
	   	 manager.update(bean);
	   	 return "redirect:list.jspx";
	    }
	    
		/**
		 * 密码修改输入页
		 * 
		 * @param request
		 * @param response
		 * @param model
		 * @return
		 */
		@RequestMapping(value = "/employee/pwd.jspx", method = RequestMethod.GET)
		public String passwordInput(Long id,HttpServletRequest request,
				HttpServletResponse response, ModelMap model) {
			Website web = SiteUtils.getWeb(request);
		   	ShopMember member=CmsUtils.getMember(request);
		   	 //用户没有登录，跳转到登陆页
		   	 if(member==null){
		   		 return ShopFrontHelper.showLogin(request, model, web);
		   	 }
		   	 model.addAttribute("member", manager.findById(id));
		   	ShopFrontHelper.setCommonData(request, model, web);
			return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_EMPLOYEE_STORE_PASSWORD), request);
		}
		
		/**
		 * 密码修改提交页
		 * 
		 * @param origPwd
		 *            原始密码
		 * @param newPwd
		 *            新密码
		 * @param email
		 *            邮箱
		 * @param nextUrl
		 *            下一个页面地址
		 * @param request
		 * @param response
		 * @param model
		 * @return
		 * @throws IOException
		 */
		@RequestMapping(value = "/employee/pwd.jspx", method = RequestMethod.POST)
		public String passwordSubmit(Long id,String origPwd, String newPwd, String email,
				String nextUrl, HttpServletRequest request,
				HttpServletResponse response, ModelMap model) throws IOException {
			Website web = SiteUtils.getWeb(request);
			ShopMember member=CmsUtils.getMember(request);
		   	 //用户没有登录，跳转到登陆页
		   	 if(member==null){
		   		 return ShopFrontHelper.showLogin(request, model, web);
		   	 }
			Long userId =manager.findById(id).getMember().getUser().getId();
			WebErrors errors = validatePassword(userId, email, newPwd, member
					.getEmail(), origPwd, request);
			if (errors.hasErrors()) {
				return FrontHelper.showError(errors, web, model, request);
			}
			userMng.updateUser(userId, newPwd, email);
			log.info("ShopMember update password: {}", member.getUsername());
			return FrontHelper.showSuccess("global.success", nextUrl, web, model,
					request);
		}
		
		private WebErrors validatePassword(Long userId, String email,
				String newPwd, String origEmail, String origPwd,
				HttpServletRequest request) {
			WebErrors errors = WebErrors.create(request);
			if (!StringUtils.isBlank(newPwd)
					&& errors.ifOutOfLength(newPwd, "password", 3, 32)) {
				return errors;
			}
			if (!userMng.isPasswordValid(userId, origPwd)) {
				errors.addErrorCode("error.passwordInvalid");
			}
//			if (errors.ifNotEmail(email, "email", 100)) {
//				return errors;
//			}
//			if (!email.equals(origEmail) && userMng.emailExist(email)) {
//				errors.addErrorCode("error.emailExist");
//				return errors;
//			}
			return errors;

		}

		@Autowired
		private UserMng userMng;
	    @Autowired
	    private RoleMng roleMng;
	    @Autowired
	    private ShopMemberMng manager;
}
